今天寫一個儲存在手機的文件
public class FileWriteActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et_name;
private EditText et_age;
private EditText et_height;
private EditText et_weight;
private CheckBox cb_marry;
private String path;
private TextView tv_read;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_file_write);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
et_name = findViewById(R.id.et_name);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
cb_marry = findViewById(R.id.cb_marry);
tv_read = findViewById(R.id.tv_read);
findViewById(R.id.btn_save).setOnClickListener(this);
findViewById(R.id.btn_read).setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId() == R.id.btn_save){
String name = et_name.getText().toString();
String age = et_age.getText().toString();
String weight = et_weight.getText().toString();
String height = et_height.getText().toString();
StringBuilder sb = new StringBuilder();
sb.append("姓名").append(name);
sb.append("\n年齡").append(age);
sb.append("\n身高").append(height);
sb.append("\n體重").append(weight);
sb.append("\n婚否").append(cb_marry.isChecked()?"是":"否");
String fileName = System.currentTimeMillis() + ".txt";
String direcyory = null;
direcyory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
path = direcyory+ File.separatorChar+ fileName;
Log.d("ning",path);
FileUtil.saveText(path, sb.toString());
ToastUtil.show(this,"保存成功");
} else if (view.getId() == R.id.btn_read) {
tv_read.setText(FileUtil.openText(path));
}
}
}
public class FileUtil {
public static void saveText(String path,String txt){
BufferedWriter os = null;
try {
os = new BufferedWriter(new FileWriter(path));
os.write(txt);
}catch (Exception e){
e.printStackTrace();
}finally {
if(os != null){
try {
os.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
public static String openText(String path){
BufferedReader is = null;
StringBuilder sb = new StringBuilder();
try {
is = new BufferedReader(new FileReader(path));
String line = null;
while ((line = is.readLine())!= null){
sb.append(line);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (is != null){
try {
is.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
return sb.toString();
}
}